

namespace AlgorithmBubbleSort {
    // show debug log
    const isDebug: boolean = true;

    // 冒泡排序(默认升序排序)
    function bubbleSort(ary: number[]) {
        const len: number = ary ? ary.length : 0;
        if (len <= 1) return;
        if (isDebug)
            console.log(`数组长度${len}，排序前数组：\n`, JSON.stringify(ary));
        for (let i = 0; i < len - 1; i++) {
            if (isDebug)
                console.log(`\n第${i}次遍历，遍历至第${len - 1 - i}个元素。`);
            for (let j = 0; j < len - 1 - i; j++) {
                let isSwap: boolean = false;
                if (ary[j] > ary[j + 1]) {
                    const temp = ary[j];
                    ary[j] = ary[j + 1];
                    ary[j + 1] = temp;
                    isSwap = true;
                }
                if (isDebug)
                    console.log(`第${j}个元素排序，是否发生交换${isSwap}，当前数组：\n`, JSON.stringify(ary));
            }
        }
    }

    function main() {
        const ary: number[] = [22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70];
        bubbleSort(ary);
    }
    main();
}